package mo.offer_special;

public class L106 {

    private static final int UNCOLORED = 0;
    private static final int RED = 1;
    private static final int GREEN = 2;
    private int[] colors;

    public boolean isBipartite(int[][] graph) {
        colors = new int[graph.length];
        for (int i = 0; i < graph.length; i++) {
            if (colors[i] == UNCOLORED) {
                if (!dfs(graph, i, RED)) {
                    return false;
                }
            }
        }
        return true;
    }

    private boolean dfs(int[][] graph, int i, int color) {
        colors[i] = color;
        int next = color == RED ? GREEN : RED;
        for (int node : graph[i]) {
            if (colors[node] == UNCOLORED) {
                if (!dfs(graph, node, next)) {
                    return false;
                }
            } else {
                if (colors[node] != next) {
                    return false;
                }
            }
        }
        return true;
    }

    public static void main(String[] args) {
        L106 test = new L106();
        System.out.println(test.isBipartite(new int[][]{{1,3}, {0,2}, {1, 3}, {0, 2}}));
    }

}
